// Learn TypeScript:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/typescript.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html

import {frameUtils} from "./FrameUtils";
import Rocker from "../rocker";
import Controls from "../controls";
import GameBoard from "../game/gameboard";
import Skillboard from "../skillboard";

const {ccclass, property} = cc._decorator;

@ccclass
export default class FrameComponent extends cc.Component {

  @property(cc.Node)
  controlsNode: cc.Node = null;
  controls: Controls = null;
  @property(cc.Node)
  skillBoardNode: cc.Node = null;
  skillBoard: Skillboard = null;
  @property(cc.Node)
  resultBoard: cc.Node = null;
  @property(cc.Node)
  gameBoard: cc.Node = null;

  // @property
  // text: string = 'hello';

  // LIFE-CYCLE CALLBACKS:
  private replay = false;

  onLoad() {
    window['frameUtils'] = frameUtils;
    frameUtils.frameComponent = this;
    this.controls = this.controlsNode.getComponent(Controls);
    this.skillBoard = this.skillBoardNode.getComponent(Skillboard);
  }

  start() {
    frameUtils.reset();
  }

  update(dt) {
    frameUtils.update();
    if (this.replay) {
      const frameData = frameUtils.getFrameData();
      this.updateControls(frameData)
    }
  }

  updateControls(frameData) {
    const controlsData = frameData.controlsData;
    if (controlsData.touchStart) {
      this.controls.onTouchStartRecord(controlsData.touchStart.id, controlsData.touchStart.startX, controlsData.touchStart.startY);
    }
    if (controlsData.touchMove) {
      this.controls.onTouchMoveRecord(controlsData.touchMove.locationX, controlsData.touchMove.locationY);
    }
    if (controlsData.touchEnd) {
      this.controls.onTouchEndRecord();
    }
  }

  startReplay() {
    this.replay = true;
    this.resultBoard.active = false;
    this.gameBoard.getComponent(GameBoard).restart();
  }
}
